import myRequest from '@/utils/request'
import {
	setToken,
	setOpenId,
	setUserCode
} from '@/utils/auth'
import store from "@/store"

// uni.login()封装
const wxLogin = function() {
	console.log('司机获取用户code~')
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success(res) {
				if (res.code) {
					setUserCode(res.code)
					resolve(res.code)
				} else {
					reject(res.errMsg);
				}
			}
		})
	})
}
//账号登录获取openid
const AppLoginGetOpenId = function() {
	/*登录提示*/
	console.log("正在获取openid~~")
	wxLogin().then(code => {
		console.log('code~~999', code)
		setUserCode(code)
		//获取openid 传入用户信息code
		myRequest({
			url: `/system/auth/get-openid-by-code?code=${code}`,
			method: 'GET',
		}).then(function(v) {
			console.log(v.data, '~~ AppLoginopenid')
			setOpenId(v.data)
			// 获取access-token
			myRequest({
				url: `/system/auth/get-access-token-by-openid?openId=${v.data}`,
				method: 'GET',
			}).then(function(w) {
				console.log(w, '~~accesstoken')
				uni.setStorageSync('accesstoken',
					w.data
				)
			}, function(error) {
				console.log(error);
			})
		})
	})
}

/*微信小程序登录*/
const wechatAppLogin = function() {
	/*登录提示*/
	console.log("正在授权~~")
	wxLogin().then(code => { // 引用uni.login()封装
		//获取openid 传入用户信息code
		myRequest({
			url: `/system/auth/get-openid-by-code?code=${code}`,
			method: 'GET',

		}).then(function(v) {
			console.log(v.data, '~~openid')
			setOpenId(v.data)
			// 调用微信登录接口  
			myRequest({
				url: `/system/auth/login-by-wx?openId=${v.data}`,
				method: 'POST',
			}).then(function(w) {
				console.log(w, '~~~~微信登录')
				uni.setStorageSync("ACCESS_TOKEN", w.data.accessToken);
				uni.setStorageSync("REFRESH_TOKEN", w.data.refreshToken);

				uni.switchTab({
					url: '/pages/index'
				})
			}, function(error) {
				console.log(999)
				console.log(error);
			})
			// 获取access-token
			myRequest({
				url: `/system/auth/get-access-token-by-openid?openId=${v.data}`,
				method: 'GET',
			}).then(function(w) {
				console.log(w, '~~accesstoken')
				uni.setStorageSync('accesstoken',
					w.data
				)
			}, function(error) {
				console.log(error);
			})
		})

	})
}

module.exports = {
	wechatAppLogin,
	AppLoginGetOpenId,
	wxLogin
}